<template>
  <div>
    <div class="text-right mb-2">
      <el-button
        size="small"
        icon="el-icon-printer"
        v-show="viewMode"
        :disabled="loading"
        @click="handlePrint"
      >
        打印
      </el-button>
      <el-button
        size="small"
        icon="el-icon-printer"
        v-show="viewMode"
        :disabled="loading"
        @click="onExportExcel"
      >
        导出
      </el-button>
    </div>

    <div ref="approvalRef" v-loading="loading" :id="printId">
      <table class="w-100">
        <tr>
          <td colspan="4">
            <h4 class="text-center">
              <div>保证金登记表</div>
            </h4>
          </td>
        </tr>
      </table>

      <table class="table table-sm table-bordered table-vertical-middle approve-table">
        <colgroup>
          <col width="20%" />
          <col width="30%" />
          <col width="20%" />
          <col width="30%" />
        </colgroup>
        <tbody>
          <tr>
            <td>
              <span class="text-danger">*</span>
              客户名称
            </td>
            <td class="report-input-td">
              <span v-if="isView || queryId">{{ related.customer_name }}</span>
              <select-self-customer
                v-model="related.customer_related_id"
                clearable
                v-else
                @change="handleCustomerSelect"
              ></select-self-customer>
            </td>
            <td>联系人</td>
            <td>{{ related.corp_name || '-' }}</td>
          </tr>
          <tr>
            <td>联系电话</td>
            <td>{{ related.mobile_no || '' }}</td>
            <td>经营地址</td>
            <td class="text-left">{{ related.address || '' }}</td>
          </tr>

          <tr>
            <td>贷款金额</td>
            <td>{{ related.reply_funds || '' }}</td>
            <td>贷款期限</td>
            <td>{{ related.months || '' }} 月</td>
          </tr>
          <tr>
            <td>放款时间</td>
            <td>{{ $utils.dateFormat(related.load_date, 'yyyy-MM-dd') || '' }}</td>
            <td>到期时间</td>
            <td>{{ $utils.dateFormat(related.load_end_date, 'yyyy-MM-dd') || '' }}</td>
          </tr>
        </tbody>
      </table>

      <bond-edit
        v-if="!tableId"
        :query-id="related.customer_related_id"
        :view-mode="viewMode"
        :related-data="related"
        :bond-data="formData"
        @success="handleSuccess"
        @dismiss="handleDismiss"
      ></bond-edit>

      <template v-else v-for="(approve, index) of approval">
        <component
          v-if="approve.show"
          v-bind="$attrs"
          :key="index"
          :query-id="related.customer_related_id"
          :table-id="tableId"
          :is="approve.cmpt"
          :bond-data="formData"
          :view-mode="viewMode || !approve.editable"
          :related-data="related"
          :approve-data="approve"
          @success="handleSuccess"
          @dismiss="handleDismiss"
        ></component>
      </template>
    </div>
  </div>
</template>

<script>
import { printA4, excelTablesExport, domHasClass } from '@vimi/utils-tool'
import SelectSelfCustomer from '@/credit/views/county/settle/bond/component/SelectSelfCustomer'
import BondEdit from '@/credit/views/county/settle/bond/component/register/BondEdit'
import { mapGetters } from 'vuex'
import { getApprove } from '@/credit/mixin/wf'
import ApproveCommon from '@/credit/views/county/settle/bond/component/refund/ApproveCommon'
export default {
  components: {
    SelectSelfCustomer,
    BondEdit,
    ApproveCommon,
  },
  props: {
    editMode: {
      type: Array,
      default: () => [1],
    },
    tableId: String,
    queryId: String,
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'bond_register',
      related: {},
      formData: {},
      approval: [],
    }
  },
  computed: {
    ...mapGetters(['user']),
    tdClass() {
      return this.isView ? '' : 'report-input-td'
    },
    printId() {
      return `project-bond-${this.tableId}`
    },
    isView() {
      return this.viewMode
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.getRelated()
      },
      immediate: true,
    },
    tableId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async handleCustomerSelect(val, related) {
      this.related = related || {}
    },
    onExportExcel() {
      this.loading = true
      excelTablesExport(this.printId, this.fileName, {
        styles: {
          // 全局样式
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        // 单元格样式，最顶级设置(styles -> dataset -> cellStyles)
        // 可以设置成 A1，或 'r-c' 的主键
        cellStyles: {},
        cols: [{ wch: 31 }, { wch: 31 }, { wch: 31 }, { wch: 31 }],
        cellHandler: ({ td, tr }) => {
          const style = {}
          if (domHasClass(tr, 'report-gray') || domHasClass(td, 'report-gray')) {
            style.fill = { fgColor: { rgb: 'FFA6A6A6' } }
          }
          if (domHasClass(tr, 'font-weight-bold') || domHasClass(td, 'font-weight-bold')) {
            style.font = { bold: true }
          }
          if (domHasClass(td, 'text-danger')) {
            if (!style.font) style.font = {}
            style.font.color = { rgb: 'FFFF0000' }
          }

          return { style }
        },
      })
        .catch(err => {
          const msg = (err && err.message) || ''
          this.$message.error(`导出失败，请重试！${msg}`)
        })
        .finally(() => {
          this.loading = false
        })
    },
    getRelated() {
      this.related = {}

      if (!this.queryId) {
        return
      }

      this.loading = true
      this.$api
        .getDataFromId(this.$serviceName, 'customer_related', this.queryId)
        .then(res => {
          this.related = res?.data ?? {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    getData() {
      this.formData = {}
      this.approve = []
      if (!this.tableId) {
        return
      }

      this.loading = true
      Promise.all([
        getApprove(
          {
            wfKey: 'BOND_APPROVAL',
            queryId: this.tableId,
            config: {
              'BOND_APPROVAL-RESB': {
                cmpt: 'bond-edit',
                rekey: null,
              },
            },
          },
          this.$store.getters.user
        ),
        this.$api.getData(this.$serviceName, this.tableName, {
          'bond_register_id.eq': this.tableId,
        }),
      ])
        .then(([approval, res]) => {
          const data = approval[0] ?? {}
          const rekey = data.process?.wfn_key ?? null
          this.approval = approval.map(item => {
            if (item.process?.wfn_key !== rekey) {
              item.rekey = rekey
            }
            return item
          })
          this.formData = res?.data?.[0] ?? {}
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleSuccess(res) {
      this.$emit('success', res)
    },

    handleDismiss() {
      this.$emit('dismiss')
    },

    handlePrint() {
      printA4(
        this.$refs.approvalRef.innerHTML,
        `
        .vertical-align-middle td {vertical-align: middle;}
        .option {min-height: 7rem;}
      `
      )
    },
  },
}
</script>

<style lang="scss" scoped>
.approve-table {
  text-align: center;
  margin-bottom: 0;
  margin-top: -1px;
  td {
    vertical-align: middle;
  }
}
</style>
